<!--
 * @Descripttion:
 * @version:
 * @Author: cxguo
 * @Date: 2019-10-01 15:50:24
 * @LastEditors: cxguo
 * @LastEditTime: 2019-10-01 17:09:40
 -->
<template>
  <div>
    <el-table
      ref="roleTable"
      v-loading="tableLoading.role"
      :data="getTableData('role')"
      style="width: 100%"
      border
      @selection-change="onSelectionChange"
    >
      <el-table-column label="#" type="selection" width="60" />
      <el-table-column label="角色名" prop="roleName" align="left" />
    </el-table>
  </div>
</template>
<script>

import { oftenuse } from '@/libs/mixins'
import { listData } from '@/api/sys/role.js'
import { getUserRoleIds } from '@/api/sys/users.js'

export default {
  name: 'SelectRole',
  mixins: [oftenuse],
  props: {
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      userRoles: []
    }
  },
  watch: {
    'userRoles': function() {
      this.setTableSelection()
    },
    'tableData.role': function() {
      this.setTableSelection()
    }
  },
  created() {
    this.setTableData('role', [])
    this.initData()
  },
  methods: {
    setTableSelection() {
      const userRoleIds = this.userRoles.map(item => { return item.roleId }) || []
      const rolesAll = this.getTableData('role') || []
      if (!userRoleIds.length && !rolesAll.length) return
      setTimeout(() => {
        rolesAll.forEach((item, index) => {
          if (userRoleIds.indexOf(item.roleId) !== -1) {
            this.$refs.roleTable.toggleRowSelection(rolesAll[index], true)
          }
        })
      }, 200)
    },
    listRoleData(params) {
      this.setTableLoading('role', true)
      listData(params = { data: {}, pageInfo: this.pageInfo }).then(res => {
        this.setTableLoading('role', false)
        if (res.data.flag) this.setTableData('role', res.data.data)
      }).catch(err => {
        console.log(err)
        this.setTableLoading('role', false)
      })
    },
    initData() {
      this.listRoleData()
      this.getUserRoleIds(this.userId)
    },
    /**
     * 获取用户的roles
     */
    getUserRoleIds(userId) {
      getUserRoleIds(userId).then(res => {
        if (res.data.flag) this.userRoles = res.data.data
        else this.$notify.error({ title: '获取用户角色失败!' })
      })
    },
    onSelectionChange(selectionData) {
      this.setTableSelectionData('role', selectionData)
    }
  }
}
</script>
